package com.hepinghospital.user.util

import android.app.Activity
import android.graphics.Color
import android.graphics.LinearGradient
import android.graphics.Shader
import android.net.Uri
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions.bitmapTransform
import com.chad.library.adapter.base.BaseQuickAdapter
import com.hjq.shape.view.ShapeEditText
import com.kingja.loadsir.core.LoadService
import com.kingja.loadsir.core.LoadSir
import com.hepinghospital.user.R
import com.hepinghospital.user.ui.widget.EmptyCallback
import com.hepinghospital.user.ui.widget.ErrorCallback
import com.hepinghospital.user.ui.widget.LoadingCallback
import com.scwang.smartrefresh.layout.SmartRefreshLayout


/**m
 * @Description: 项目中自定义类的拓展函数
 * @Author: lzp
 * @CreateDate: 2021/6/5 19:35
 * @UpdateRemark: 更新说明
 */

/**
 * 文字设置渐变颜色
 */
fun TextView.setGradientTextColor(text: String) {
    val shader: Shader = LinearGradient(
        0f, 0f, 0f, this.lineHeight.toFloat(),
        Color.parseColor("#3EDDD4"), Color.parseColor("#158CF4"), Shader.TileMode.REPEAT
    )
    paint.shader = shader
    setText(text)
}


fun ImageView.load(url: String) {
    Glide.with(context)
        .load(url)
        .transition(DrawableTransitionOptions.withCrossFade(500))
        .into(this)
}

fun ImageView.load(uri: Uri) {
    Glide.with(context)
        .load(uri)
        .transition(DrawableTransitionOptions.withCrossFade(500))
        .into(this)
}

/**
 * 带圆角的图片
 */
fun ImageView.load(url: String, radius: Int) {
    Glide.with(context)
        .load(url)
        .apply(bitmapTransform(RoundedCorners(radius)))
        .transition(DrawableTransitionOptions.withCrossFade(500))
        .into(this)
}

/**
 * 加载圆形图片
 */
fun ImageView.loadCircleCrop(url: String) {
    Glide.with(context)
        .load(url)
        .apply(bitmapTransform(CircleCrop()))
        .transition(DrawableTransitionOptions.withCrossFade(500))
        .into(this)
}

/**
 * 设置错误提示信息
 */
fun LoadService<*>.setErrorText(message: String) {
    if (message.isNotEmpty()) {
        this.setCallBack(ErrorCallback::class.java) { _, view ->
            view.findViewById<TextView>(R.id.error_text).text = message
        }
    }
}

/**
 * 设置错误布局
 * @param message 错误布局显示的提示内容
 */
fun LoadService<*>.showError(message: String = "") {
    this.setErrorText(message)
    this.showCallback(ErrorCallback::class.java)
}

/**
 * 设置空布局
 */
fun LoadService<*>.showEmpty() {
    this.showCallback(EmptyCallback::class.java)
}

/**
 * 设置加载中
 */
fun LoadService<*>.showLoading() {
    this.showCallback(LoadingCallback::class.java)
}

fun loadServiceInit(
    view: View,
    title: String = "",
    buttonText: String = "",
    buttonAction: (() -> Unit)? = null,
    callback: (() -> Unit)? = null
): LoadService<Any> {
    val loadSir = LoadSir.getDefault().register(view) {
        //点击重试时触发的操作
        callback?.invoke()
    }
    loadSir.setCallBack(EmptyCallback::class.java) { _, emptyView ->
        emptyView.findViewById<TextView>(R.id.tv_tip).text = title
        if (buttonText.isEmpty()) {
            emptyView.findViewById<TextView>(R.id.tv_save).visibility = View.GONE
        } else {
            emptyView.findViewById<TextView>(R.id.tv_save).apply {
                text = buttonText
                setOnClickListener {
                    buttonAction?.invoke()
                }
            }
        }
    }
    loadSir.showSuccess()
    return loadSir
}

//绑定普通的Recyclerview
fun RecyclerView.init(
    layoutManger: RecyclerView.LayoutManager,
    bindAdapter: RecyclerView.Adapter<*>,
    isScroll: Boolean = true
): RecyclerView {
    layoutManager = layoutManger
    setHasFixedSize(true)
    adapter = bindAdapter
    isNestedScrollingEnabled = isScroll
    return this
}

/**
 * 隐藏软键盘
 */
fun hideSoftKeyboard(activity: Activity?) {
    activity?.let { act ->
        val view = act.currentFocus
        view?.let {
            val inputMethodManager =
                act.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(
                view.windowToken,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }
}

/**
 * 列表数据加载
 */
fun <T> loadListData(
    data: MutableList<T>,
    baseQuickAdapter: BaseQuickAdapter<T, *>,
    loadService: LoadService<*>,
    refreshLayout: SmartRefreshLayout,
    page: Int,
    isSuccess: Boolean
) {
    //成功
    if (isSuccess) {
        //是否第一页
        if (page == 1) {
            //数据为空
            if (data.isEmpty()) {
                loadService.showEmpty()
            } else {
                baseQuickAdapter.setList(data)
                loadService.showSuccess()
            }
            refreshLayout.finishRefresh(true)
        } else {
            //不是第一页
            baseQuickAdapter.addData(data)
            loadService.showSuccess()
            refreshLayout.finishLoadMore(true)
        }
    } else {
        //失败
        if (page == 1) {
            loadService.showError()
            refreshLayout.finishRefresh(false)
        } else {
            loadService.showSuccess()
            refreshLayout.finishLoadMore(false)
        }
    }
}


fun <T> loadListData(
    data: ListDataUiState<T>,
    baseQuickAdapter: BaseQuickAdapter<T, *>,
    loadService: LoadService<*>,
//        recyclerView: RecyclerView,
    refreshLayout: SmartRefreshLayout,
    page: Int
) {
    if (data.isSuccess) {
        //成功
        when {
            //第一页并没有数据 显示空布局界面
            data.isFirstEmpty -> {
                loadService.showEmpty()
                refreshLayout.finishRefresh(true)
            }
            //是第一页
            data.isRefresh -> {
                baseQuickAdapter.setList(data.listData)
                loadService.showSuccess()
                refreshLayout.finishRefresh(true)
            }
            //不是第一页
            else -> {
                baseQuickAdapter.addData(data.listData)
                loadService.showSuccess()
                refreshLayout.finishLoadMore(true)
            }
        }
    } else {
        //失败
        if (data.isRefresh) {
            //如果是第一页，则显示错误界面，并提示错误信息
            loadService.showError(data.errMessage)
        } else {
//            recyclerView.loadMoreError(0, data.errMessage)
        }
    }
}

fun EditText.isEmptyContent(): Boolean {
    return this.text.toString().trim().isEmpty()
}

fun EditText.getContent(): String {
    return this.text.toString().trim()
}

fun ShapeEditText.isEmptyContent(): Boolean {
    return this.text.toString().trim().isEmpty()
}

fun ShapeEditText.getContent(): String {
    return this.text.toString().trim()
}

fun TextView.getContent(): String {
    return this.text.toString().trim()
}

fun TextView.isEmptyContent(): Boolean {
    return this.text.toString().trim().isEmpty()
}